package namespace

import (
	"errors"

	"gddgame.cc/galaxy/binocle"
	//"gddgame.cc/galaxy/common/service/pathfinding"
	"gddgame.cc/galaxy/core/sdk"
	"gddgame.cc/galaxy/project/breeder/breeder/controller"
	"gddgame.cc/galaxy/project/breeder/breeder/model"
	"gddgame.cc/galaxy/satellite/formula/nebula"
	"gddgame.cc/galaxy/server/composer"
)

const (
	_ nebula.NSE = iota
	MapDownload
	MapAgain
	MapGetNo
)

/*
 游戏地图管理:
 可以用于做地图服务器：
 当前可用地图（服务器列表），服务器状态
*/
// pvp以及pve地图访问接口
func MapHandler(builder composer.Builder, client *sdk.AppClient, namespace nebula.Namespace) {
	var agent binocle.App
	builder.Factory("agent", &agent)

	namespace.SetCompress(true)

	if err := namespace.Connect(func(socket *nebula.Socket, next nebula.Next) {
		var openId string
		err := socket.Get("open_id", &openId)
		if err != nil {
			_ = next(errors.New("Auth error"))
			return
		}
		_ = next(nil)

	}); err != nil {
		builder.Error(err)
	}

	_ = namespace.On(MapDownload, func(req *nebula.Request, mapId int, version int) {
		mapItem, err := controller.GetMap(req, mapId)
		if err != nil {
			return
		}
		if mapItem.Version <= version {
			return
		}
		req.Response(mapItem.Data)
	})

	_ = namespace.On(MapAgain, func(req *nebula.Request, mapId int) {
		// 查询已有的地图
		var mapNo *model.MapNo
		var err error
		create := false
		mapItem, err := controller.GetMap(req, mapId)
		if err != nil {
			return
		}
		if mapId == 0 {
			var mapNoId string
			if agent.Namespace() == "local" {
				mapNoId = mapItem.EncodeNo(0)
			} else {
				mapNoId = mapItem.EncodeNo(mapItem.No)
			}
			_, mapNo, _ = controller.GetMapNo(req, mapNoId)
			if mapNo == nil {
				mapNo, err = controller.CreateNo(req, mapItem)
				if err != nil {
					return
				}
				create = true
			}
		} else {
			mapNo, err = controller.CreateNo(req, mapItem)
			if err != nil {
				return
			}
			create = true
		}
		if create {
			controller.Env.CooperateManager.StartMap(mapNo.Id, "")
		}

		// 获取该地图，并清除地图数据，重新启动
		req.Response(mapNo.Id)
	})
	_ = namespace.On(MapGetNo, func(req *nebula.Request, mapNoId string) {
		_, mapNo, _ := controller.GetMapNo(req, mapNoId)
		//fmt.Println("get no", mapNo.Status)
		if mapNo != nil {
			req.Response(mapNo.Status)
		} else {
			req.Response(false)
		}
	})
}
